package com.lenovo.rc.sil.wangdwa.learning;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;



public class ContentProviderDemoActivity extends Activity implements OnClickListener{
	
	private EditText mTxtContent = null;
	
	private ContentResolver mCR = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btnQuery = (Button)findViewById(R.id.BTN_QUERY);
        btnQuery.setOnClickListener(this);
        
        // what to do with the EditText
        mTxtContent = (EditText)findViewById(R.id.TXT_CONTENT);
        
        mCR = this.getContentResolver();
        
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()){
		case R.id.BTN_QUERY:
			clearText();
			doQuery();
			break;
		}
	}

	private void clearText() {
		// TODO Auto-generated method stub
		Log.d(this.getClass().getName(), "clearText()");
		
		mTxtContent.setText("");
		
		
	}

	private void doQuery() {
		// TODO Auto-generated method stub
		Log.d(this.getClass().getName(), "doQuery()");
		
		Uri srcUri = ContentUris.withAppendedId(MyDB.CONTENT_URI, MyDB.ALL_ROWS);
		Cursor c = mCR.query(srcUri, null, null, null, null);
		
		if (c == null) {
			Toast.makeText(this, "fail to get the cursor", Toast.LENGTH_LONG).show();
			return;
		}
		
		c.moveToFirst();
		
		while(!c.isAfterLast()) {
			printText("_id: " + c.getInt(0));
			printText("name: " + c.getString(1));
			printText("sex: " + c.getString(2));
			
			c.moveToNext();
		}
		
		c.close();
		
	}

	private void printText(String string) {
		// TODO Auto-generated method stub
		mTxtContent.append(string);
		mTxtContent.append("\n");
	}




}